<template>
  <el-form ref="formRef" size="small" :model="form" :rules="rules">
    <el-form-item prop="name">
      <div class="yc-da">
        <el-input
          v-model="form.name"
          clearable
          class="yc-mr-10"
          placeholder="请输入您要添加的事项"
        ></el-input>
        <el-button type="primary" @click="handleAddItem">添加事项</el-button>
      </div>
    </el-form-item>
  </el-form>
</template>
<script>
import { mapMutations, mapState } from "vuex";
import { nanoid } from "nanoid";
export default {
  data() {
    const checkName = (rule, value, cb) => {
      const name = value ? value.trim() : undefined;
      if (!name) {
        cb(new Error("请输入要添加的事项"));
      } else {
        cb();
      }
    };
    return {
      form: {
        name: undefined,
      },
      rules: {
        name: [{ validator: checkName, trigger: ["blur", "change"] }],
      },
    };
  },
  computed: {
    ...mapState(["todoList"]),
  },
  methods: {
    ...mapMutations(["addItem"]),
    handleAddItem() {
      this.$refs["formRef"].validate((valid) => {
        if (!valid) return;
        const { name } = this.form;
        const flag = this.todoList.find((v) => v.name === name);
        if (flag) {
          this.$message.warning("该事项已存在,请重新添加事项!");
          this.$refs["formRef"].resetFields();
          return;
        }
        const item = {
          id: nanoid(),
          name: name,
          finished: false,
        };
        this.addItem(item);
        this.$message.success("添加事项成功!");
        this.$refs["formRef"].resetFields();
      });
    },
  },
};
</script>
